package com.xsdl.giteespringbootautoconfigure;

import com.xsdl.giteespringbootautoconfigure.config.GiteeProperty;
import com.xsdl.giteespringbootautoconfigure.util.HttpUtil;
import com.xsdl.giteespringbootautoconfigure.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Configuration
@EnableConfigurationProperties(GiteeProperty.class)
public class GiteeAutoConfiguration {

    @Autowired
    private GiteeProperty property;

    @Autowired
    private RestTemplate restTemplate;

    public GiteeProperty getProperty() {
        return property;
    }

    public Map<String, Object> getGiteeAccessToken(String code) {
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code"
                + "&code=" + code
                + "&client_id=" + property.getClientId()
                + "&redirect_uri=" + property.getRedirectUri()
                + "&client_secret=" + property.getClientSecret();
        String responseJson = HttpUtil.sendPostRequest(restTemplate, url, null);
        Map<String, Object> responseMap = JsonUtil.parseToMap(responseJson);
        Object accessToken = responseMap.get("access_token");
        if (accessToken == null) {
            throw new RuntimeException("获取accessToken失败");
        }
        return responseMap;
    }

    public Map<String, Object> getGiteeUserInfo(String token) {
        String responseJson = HttpUtil.sendGetRequest(restTemplate, "https://gitee.com/api/v5/user?access_token=" + token);
        Map<String, Object> responseMap = JsonUtil.parseToMap(responseJson);
        Object openId = responseMap.get("id");
        if (openId == null) {
            return null;
        }
        return responseMap;
    }

}
